package com.shop.handler;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.entity.AttributeDTO;
import com.shop.entity.ImageDTO;
import com.shop.entity.SkuDTO;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class JsonArrayTypeHandler extends BaseTypeHandler<List<?>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<?> parameter, JdbcType jdbcType) {
        try {
            String jsonStr = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonStr);
        } catch (JsonProcessingException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonStr = rs.getString(columnName);
        try {
            return parseJsonArray(jsonStr, resolveTargetClass(columnName));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return List.of();
    }

    @Override
    public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return List.of();
    }

    private Class<?> resolveTargetClass(String columnName) {
        return switch (columnName) {
            case "skus" -> SkuDTO.class;
            case "images" -> ImageDTO.class;
            case "attributes" -> AttributeDTO.class;
            default -> Object.class;
        };
    }

    private List<?> parseJsonArray(String jsonStr, Class<?> targetClass) throws JsonProcessingException {
        if (StringUtils.isEmpty(jsonStr)) return Collections.emptyList();
        return objectMapper.readValue(jsonStr,
                objectMapper.getTypeFactory().constructCollectionType(List.class, targetClass));
    }
}